import {
	createPinia
} from 'pinia'
import {
	defineStore
} from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

export const useCounterStore = defineStore('counter', {
	state: () => ({
		eastPound: {
			weight: 0,
			autoLicense: ''
		}, // 实时数据（临时）
		westPound: {
			weight: 0,
			autoLicense: ''
		}, // 实时数据（临时）
		// 新增：按车牌绑定的完整过磅数据（key=车牌，value=过磅数据）
		licenseWeighData: {
			'1001': {}, // 东磅：{ [license]: { weighingType, aWeight, weightStatus, ... } }
			'1002': {} // 西磅：同上
		},
		persistedData: { // 原有持久化数据（保留）
			licensePlates: {
				'1001': '',
				'1002': ''
			},
			isManualInput: {
				'1001': false,
				'1002': false
			},
			lastOperateTime: {
				'1001': 0,
				'1002': 0
			}
		},
		infoObj:{
			toBeSupplemented:0,//待补录
			pendingReview:0,//待审核
		}
	}),
	persist: {
		paths: ['persistedData', 'licenseWeighData'], // 新增licenseWeighData持久化
		storage: localStorage,
		key: 'weighing_system_data'
	},
	actions: {
		// 更新待办
		updateInfoObj(data){
			if (data) {
			    // 若data中存在对应属性则更新，否则保留原值（避免意外覆盖）
			    this.infoObj.toBeSupplemented = data.toBeSupplemented ?? this.infoObj.toBeSupplemented;
			    this.infoObj.pendingReview = data.pendingReview ?? this.infoObj.pendingReview;
			  }
			
		},
		// 修复1：更新实时数据时，同步保存车牌到持久化存储（解决车牌仅推送一次丢失问题）
		updatePoundRealTime(data) {
		  const {
		    loadometerNumber,
		    weight,
		    autoLicense, // 允许为undefined（无车牌）
		    weighingType = 1,
		    weightStatus = 0
		  } = data;
		
		  // 仅拦截“无磅房编号”的情况，不再拦截“无车牌”
		  if (!loadometerNumber) return;
		
		  // 1. 更新实时显示数据（关键：无车牌时保留原车牌，仅更新重量）
		  if (loadometerNumber === '1001') {
		    this.eastPound = {
		      weight: weight ?? 0, // 有重量则更新，无则保留原重量
		      autoLicense: autoLicense ?? '' // 有车牌则更新，无则保留原车牌
		    };
			
		  } else if (loadometerNumber === '1002') {
		    this.westPound = {
		      weight: weight ?? 0,
		      autoLicense: autoLicense ?? ''
		    };
		  }
		
		  // 2. 仅当有车牌时，才按车牌存储完整数据（无车牌时跳过，避免空key问题）
		  if (autoLicense) {
		    const poundKey = loadometerNumber;
		    const licenseKey = autoLicense;
		
		    // 初始化该车牌的数据（原有逻辑不变）
		    if (!this.licenseWeighData[poundKey][licenseKey]) {
		      this.licenseWeighData[poundKey][licenseKey] = {
		        weighingType: 1,
		        aWeight: 0,
		        secondWeight: 0,
		        weightStatus: 0,
		        lastUpdateTime: 0
		      };
		    }
		
		    // 更新该车牌的具体数据（原有逻辑不变）
		    const targetData = this.licenseWeighData[poundKey][licenseKey];
		    targetData.weighingType = weighingType;
		    targetData.lastUpdateTime = Date.now();
		
		    if (weightStatus === 0 || weightStatus === 1) {
		      targetData.aWeight = weight ?? targetData.aWeight; // 有重量则更新
		      targetData.weightStatus = 1;
		    } else if (weightStatus === 2) {
		      targetData.secondWeight = weight ?? targetData.secondWeight;
		      targetData.weightStatus = 2;
		    }
		
		    // 3. 有车牌时才更新持久化车牌（原有逻辑不变）
		    this.persistedData.licensePlates[poundKey] = autoLicense;
		    this.persistedData.lastOperateTime[poundKey] = Date.now();
		  }
		},
		// 新增2：根据磅房+车牌，获取绑定的完整过磅数据
		getLicenseWeighData(loadometerNumber, license) {
			return this.licenseWeighData[loadometerNumber][license] || null;
		},

		// 新增3：删除指定磅房+车牌的数据（车辆下磅时调用）
		clearLicenseWeighData(loadometerNumber, license) {
			if (this.licenseWeighData[loadometerNumber][license]) {
				delete this.licenseWeighData[loadometerNumber][license];
			}
		},

		// 完全保留你原有的所有方法，不做任何修改
		saveLicensePlate(data) {
			const {
				loadometerNumber,
				autoLicense,
				isManual = false
			} = data
			this.persistedData.licensePlates[loadometerNumber] = autoLicense
			this.persistedData.isManualInput[loadometerNumber] = isManual
			this.persistedData.lastOperateTime[loadometerNumber] = Date.now()

			if (loadometerNumber === '1001') {
				this.eastPound.autoLicense = autoLicense
			} else {
				this.westPound.autoLicense = autoLicense
			}
		},

		clearPoundData(loadometerNumber) {
			this.persistedData.licensePlates[loadometerNumber] = ''
			this.persistedData.isManualInput[loadometerNumber] = false
			this.persistedData.lastOperateTime[loadometerNumber] = 0

			if (loadometerNumber === '1001') {
				this.eastPound = {
					weight: 0,
					autoLicense: ''
				}
			} else {
				this.westPound = {
					weight: 0,
					autoLicense: ''
				}
			}
		},

		getPersistedLicense(loadometerNumber) {
			return this.persistedData.licensePlates[loadometerNumber] || ''
		},

		isManual(loadometerNumber) {
			return this.persistedData.isManualInput[loadometerNumber]
		},
		// 清空车牌
		clearPersistedLicense(num,License) {
			
			this.persistedData.licensePlates[num]=License
		},
	}
})

export default pinia